<?php
namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Mockery\Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\RequestBackController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CheckController;
use App\aliyun\api_demo\SmsDemo;

class UserController extends Controller
{
    /**登录
     * @param
     * post         Login           登录名
     * post         PassWord        登录密码
     * @return array
     */
    public function Login($request)
    {
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['Login','PassWord']))
        {
            return RequestBackController::Structure(502);
        }
        $user = DB::table('yl_user')->where(function($quest) use($pos){
            $quest->where('user_login',$pos['Login'])->orwhere('user_mobile',$pos['Login']);
        })->where('user_password',base64_encode($pos['PassWord']))->first();
        if(!CheckController::Nonempty($user))
        {
            return RequestBackController::Structure(203);
        }
        else
        {
			if($user->user_able!=1)
			{
				return RequestBackController::Structure(210);
			}
            $data['UserToken']=$this->GetToken($user->user_login,$user->group_id,$user->purview_id);
            $data['GroupId']=$user->group_id;
            $data['UserName']=$user->user_name;
            $data['UserId']=$user->user_id;
            $data['UserLogin']=$user->user_login;
            return RequestBackController::Structure(101,$data);
        }
    }
    public function UserList($request)
    {
        if(!CheckController::CheckUser($request)){
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        $page = isset($pos['page']) ? $pos['page']  : 1;
        $pageSize = isset($pos['pageSize']) ? $pos['pageSize'] : 10;
        $offset = ($page - 1) * $pageSize;
        if(!CheckController::CheckParameter($pos,['MenuId'])){
            return RequestBackController::Structure(502);
        }
        $Purview = new PurviewController();
        if($Purview->PurviewVerdict($request,$pos['MenuId'])!='All'){
            return RequestBackController::Structure(503);
        }
        else{
            $res=DB::table('yl_user')->select('user_id as UserId','user_name as UserName','user_mobile as UserMobile','purview_id as PurviewId','group_id as GroupId','user_able as UserAble');
            $count =$res->count();
            $res=$res->offset($offset)->limit($pageSize)
                        ->get()->map(function ($val){
                            $val = (array)$val;
                            return $val;
                        })
                        ->toArray();
            $sum_page = ceil($count/$pageSize);  //总页码
            if($page > $sum_page && $sum_page > 0 ){
                return RequestBackController::Structure(301);
            }else{
                if (isset($res)) {
                    $results['Count'] = $count;
                    $results['List'] = $res;
					return RequestBackController::Structure(501,$results);
                }else{
					return RequestBackController::Structure(504);
				}
            }
            
        }
    }
    /**退出登录
     * @param
     * header         UserLogin       登录名
     * header         GroupId    登录密码
     * @return array
     */
    public function Logout($request)
    {
        $UserLogin = $request->header('UserLogin') ? $request->header('UserLogin') : '';
        $GroupId = $request->header('GroupId') ? $request->header('GroupId') : '';
        $redis = app('redis.connection');
        $redis->DEL($UserLogin .'G'.$GroupId.'_token');
        $redis->DEL($UserLogin .'G'.$GroupId.'_purview');
        return true;
    }
    //注册用户
    public function RegisterUser($request)
    {
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['PhoneNumber','PassWord','Code','Name']))
        {
            return RequestBackController::Structure(502);
        }
        $_temp=DB::table('yl_user')->where('user_name',$pos['PhoneNumber'])->orwhere('user_mobile',$pos['PhoneNumber'])->first();
        if(!empty($_temp))
        {
            return RequestBackController::Structure(207);
        }
        else
        {
            $redis = app('redis.connection');
            $_temp_Code=$redis->get($pos['PhoneNumber'].'Code');
            if(!empty($_temp_Code)&&$_temp_Code==$pos['Code'])
            {
                $arr=['user_name'=>$pos['Name'],
                    'user_login'=>$pos['PhoneNumber'],
                    'user_mobile'=>$pos['PhoneNumber'],
                    'user_password'=>base64_encode($pos['PassWord']),
                    'user_able'=>0,
                    'register_time'=>time()
                ];
                DB::table('yl_user')->insert($arr);
                return RequestBackController::Structure(101);
            }
            else
            {
                return RequestBackController::Structure(203);
            }
        }
    }
    //用户信息修改
    public function UserUpdate($request)
    {
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId','Name','PhotoPath']))
        {
            return RequestBackController::Structure(502);
        }
        $arr['user_name']=$pos['Name'];
		$arr['user_img']=$pos['PhotoPath'];//头像保存
        if(CheckController::CheckParameter($pos,['PhoneNumber','Code'])&&!empty($pos['Code']))//,'PassWord'
        {
            $redis = app('redis.connection');
            $_temp_Code=$redis->get($pos['PhoneNumber'].'Code');
            if(!empty($_temp_Code)&&$_temp_Code==$pos['Code'])
            {
                $arr['user_mobile']=$pos['PhoneNumber'];
                //$arr['user_password']=base64_encode($pos['PassWord']);
            }
            else
            {
                return RequestBackController::Structure(203);
            }
        }
        DB::table('yl_user')->where('user_id',$pos['UserId'])->update($arr);
        return RequestBackController::Structure(101);
    }
	public function CodeCheck($request)
	{
		$pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId','Code']))
        {
            return RequestBackController::Structure(502);
        }
		$user=DB::table('yl_user')->where('user_id',$pos['UserId'])->first();
		$redis = app('redis.connection');
        $_temp_Code=$redis->get($user->user_mobile.'Code');
		if(!empty($_temp_Code)&&$_temp_Code==$pos['Code'])
		{
			return RequestBackController::Structure(101);
		}
		else
		{
			return RequestBackController::Structure(503);
		}
		
	}
	//用户个人信息
    public function UserInfo($request){
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId'])){
            return RequestBackController::Structure(502);
        }else{
           $user =  DB::table('yl_user')->select('user_id as UserId','user_name as UserName','user_mobile as UserMobile','user_img as UserImg')->where('user_id',$pos['UserId'])->first();
           if (isset($user)) {
              return RequestBackController::Structure(501,$user);
           }
           else{
            return RequestBackController::Structure(505);
           }

        }
        
    }

    //验证码
    public function UserCode($request)
    {
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['PhoneNumber']))
        {
            return RequestBackController::Structure(502);
        }
        if(!preg_match('/^1[34578]\d{9}$/', $pos['PhoneNumber']))
        {
            return RequestBackController::Structure(503);
        }
        $SmsDemo=new SmsDemo();
        $redis = app('redis.connection');
        $Code=$redis->get($pos['PhoneNumber'].'Code');
        if(empty($Code))
        {
            $Code=rand(0,9).rand(0,9).rand(0,9).rand(0,9);
            $response = $SmsDemo::sendSms($pos['PhoneNumber'],$Code);
            if($response->Message=='OK')
            {
                $redis->setex($pos['PhoneNumber'].'Code',60,$Code);
                return RequestBackController::Structure(201);
            }
            else
                return RequestBackController::Structure(208);
        }
        else
            return RequestBackController::Structure(209);
    }
    public function _UserCode($request)
    {
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId']))
        {
            return RequestBackController::Structure(502);
        }
        $res=DB::table('yl_user')->where('user_id',$pos['UserId'])->first();
        $pos['PhoneNumber']=$res->user_mobile;
        $SmsDemo=new SmsDemo();
        $redis = app('redis.connection');
        $Code=$redis->get($pos['PhoneNumber'].'Code');
        if(empty($Code))
        {
            $Code=rand(0,9).rand(0,9).rand(0,9).rand(0,9);
            $response = $SmsDemo::sendSms($pos['PhoneNumber'],$Code);
            if($response->Message=='OK')
            {
                $redis->setex($pos['PhoneNumber'].'Code',300,$Code);
                return RequestBackController::Structure(201);
            }
            else
                return RequestBackController::Structure(208);
        }
        else
            return RequestBackController::Structure(209);
    }

    protected function GetToken($user_login,$GroupId,$purview_id)
    {
        $time=date('Y-m-d',time());//date('Y-m-d_h-i-s',time());
        $f_font=substr($user_login, 0);
        $l_font=substr($user_login, -1);
        /** 正式数据 **/ $font=md5($f_font.$time.$l_font);
///** 测试数据 **/        $font='abcdefg1234567';
        $redis = app('redis.connection');
        //$redis->SETEX($this->LoginName.'_'.$Nickname.'_token',$this->toekn_expiration,$UToken);
        $redis->SET($user_login.'G'.$GroupId.'_token',$font);
        $redis->SET($user_login.'G'.$GroupId.'_purview',$purview_id);
        DB::table('yl_user')->where('user_login',$user_login)->update(['last_login'=>time()]);
        return $font;
    }
    protected function test()
    {
        return RequestBackController::Structure(101);
    }


  
}